package com.mooc.lib_network.interceptor

import android.util.Log
import com.google.gson.Gson
import com.mooc.lib_network.entity.BaseEntity
import com.mooc.lib_network.entity.ConvertEntity
import com.mooc.lib_network.entity.LoginEntity
import okhttp3.Interceptor
import okhttp3.MediaType
import okhttp3.Response
import okhttp3.ResponseBody
import org.json.JSONObject

class JSONConcertInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        var response = chain.proceed(chain.request())
        //response body中得json下得\"去掉
        var body = response.body()
        var str = body!!.string()
        val map = HashMap<String,Any>()
        val valuesMap = HashMap<String,Any>()
        val convertEntity = Gson().fromJson(str,ConvertEntity::class.java)
        var values = convertEntity.values
        val job = JSONObject(values)
        val it = job.keys()
        while (it.hasNext()){
            val key = it.next()
            valuesMap.put(key,job.get(key))
        }
        map["values"] = valuesMap
        map["statuesCode"] = convertEntity.statuesCode
        map["msg"] = convertEntity.msg
        map["home"] = convertEntity.home
        //去除转义字符后得body
        var newBody : ResponseBody = ResponseBody.create(
                MediaType.parse("application/json"),Gson().toJson(map).toString())
        var builder = Response.Builder()
        builder.request(chain.request())
        builder.code(200)
        builder.message(response.message())
        builder.protocol(response.protocol())//http1.1
        builder.body(newBody)//响应体
        return builder.build()
    }
}